<title>数据查询</title>
<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb" lay-separator=">">
        <a lay-href=""><i class="layui-icon layui-icon-locate"></i>您当前的位置：</a>
        <a><cite class="first-breadcrumb">考勤管理</cite></a>
        <a><cite class="second-breadcrumb">考勤查询</cite></a>
    </div>
</div>

<div class="layui-fluid custom-dataSearch-page">
    <div class="layui-row layui-col-space10">
        <div class="layui-col-md2 layui-col-lg2 left-side">
            <div class="layui-card">
                <div class="layui-card-header">
                    <img src="../../../../dist/style/res/formFill/tem-task.png" class="card-header-icon"/>
                    <span class="card-header-title">查询区</span>
                </div>
                <div class="layui-card-body task-body">
                    <!-- <div style="padding: 0 10px">
                        <button class="layui-btn layui-btn-normal layui-btn-sm layui-btn-urge layui-btn-disabled T-btn" data-target="urge">
                            <i class="layui-icon layui-icon-release"></i>催办
                        </button>
                    </div> -->
                    <ul id="treeDemo" class="ztree"></ul>
                </div>
            </div>
        </div>
        <div class="layui-col-md10 layui-col-lg10 right-side">
            <div id="layui-query-box" class="layui-form" lay-filter="query-condition-filter"></div>
            <div class="layui-card form-box">
                <div class="layui-card-header" style="padding: 0 9px 6px 9px;">
                    <div class="layui-inline">
                        <button class="layui-btn T-btn btn-subform" data-target="submit">导出数据</button>
                        <button class="layui-btn query-btn" id="query">查询</button>
                    </div>
                    <div class="layui-inline kq-time" style="display: none;">考勤时间：<span class="kq-starttime"></span>~<span class="kq-endtime"></span></div>
                </div>
                <div class="layui-card-body" style="padding: 0;">
                    <div class="layui-tab layui-form layui-tab-card otherForm-content" lay-filter='tabSwitch'>
                        <ul class="layui-tab-title form-tab-title"></ul>
                        <div class="unit-radios" id="dept"></div>
                        <div class="layui-tab-content form-tab-content"></div>
                    </div>
                    <div id="data-dataSearch-kqform" class="kqform kqform-content"></div>
                </div>
            </div>
        </div>
    </div>
</div>

    <!-- 工具栏 -->
    <script type="text/html" id="modify-form">
        {{# if(d.model && d.model != 'insert'){ }}
            <button class="checkLine" lay-event="check" lay-tips="查看记录"><i class="layui-icon layui-icon-form"></i></button>
        {{# } }}
    </script>

    <!-- 查询条件模板 -->
    <script type="text/html" id="queryExihibt">
            <div class="query-box">
                <div class="layui-row query-condition">
                    <div class="layui-col-md12 left-card-body">
                        {{# if(d && d.length > 0){ }}
                            {{# layui.each(d, function(index, item){ }}
                                <div class="layui-inline">
                                    <label class="layui-form-label" lay-tips="{{item.fieldname}}">{{item.fieldname}}：</label>
                                    {{# if(item.isSelect){ }}
                                        <div class="layui-input-inline">
                                            <select lay-ignore name={{item.fieldenglish}} datatype={{item.datatype}}>
                                                <option value="">请选择数据</option>
                                                {{# layui.each(item.selectData, function(i, content){ }}
                                                    <option value="{{content.text}}">{{content.text}}</option>
                                                {{# }) }}
                                            </select>
                                        </div>
                                    {{# }else if(item.datatype == 'date'){ }}
                                        <div class="layui-input-inline" style="width: 120px;">
                                            <input type="text" name={{item.fieldenglish}} datatype={{item.datatype}} placeholder="开始时间" autocomplete="off" class="layui-input condition-starttime">
                                        </div>
                                        <div class="layui-input-inline" style="width:5px;">-</div>
                                        <div class="layui-input-inline" style="width: 120px;">
                                            <input type="text" name={{item.fieldenglish}} datatype={{item.datatype}} placeholder="结束时间" autocomplete="off" class="layui-input condition-endtime">
                                        </div>
                                    {{# }else{ }}
                                        <div class="layui-input-inline">
                                            <input type="text" name={{item.fieldenglish}} datatype={{item.datatype}} autocomplete="off" class="layui-input">
                                        </div>
                                    {{# } }}
                                </div>
                            {{# }) }}
                        {{# }else{ }}
                            <div class="no-data-tips" style="margin-top:10px;"><img src="/src/style/res/about/empty.png"><p style="color:#DBDBDB;">无查询条件</p></div>
                        {{# } }}
                    </div>
                </div>
            </div>
    </script>

     <!-- 单位单选框 -->
    <script type="text/html" id="unitRadios">
        {{#  if(d && d.length > 0){ }}
            {{# layui.each(d, function(index, item){ }}
                <input type="radio" name="dept" value="{{item.dept_id}}" title="{{item.dept_name}}" lay-filter="custom-unit-radio" {{item.checked ? "checked" : ""}} />
            {{# }) }}
        {{#  } }}
    </script>

<style>
    .left-side .layui-card{
        height: 842px;
        border-radius: 4px;
        padding: 0 13px 0 20px;
        background: #F2F7FD;
        overflow: hidden;
    }
    .layui-card-header{
        height: 34px;
        border-bottom: 1px solid #D2D2D2;
        padding: 0 0 6px 0;
        line-height: 40px;
    }
    .card-header-icon{
        width: 18px;
        height: 18px;
    }
    .card-header-title{
        line-height: 30px;
        margin-left: 8px;
    }
    .task-body{
        height: 765px;
        background: #FAFCFF;
        border: 1px solid #A3C4ED;
        border-radius: 5px;
        margin-top: 10px;
        padding: 5px 0;
    }
    .layui-btn-urge{
        margin-left: 13px;
        background-color: #2669B1;
    }
    .ztree{
        height: 97%;
        overflow: scroll;
    }
    .ztree *{
        padding: 0;
        font-size: 15px;
        font: inherit;
    }
    .query-box{
        min-height: 146px;
        background: #FAFCFF;
        border-radius: 5px;
        border: 1px solid #D5E4F5;
        margin-bottom: 13px;
        box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
    }
    .form-box{
        height: 678px;
        background: #F2F7FD;
        border-radius: 4px;
        border: 1px solid #90ABCD;
        overflow: auto;
    }
    .select-form-header{
        position: relative;
    }
    .card-header-right{
        position: absolute;
        right: 0;
        top: 0;
    }
    .layui-card .layui-tab{
        margin-top: 13px;
        z-index: 9999;
    }
    .layui-tab-card>.layui-tab-title{
        background: #fff;
    }
    .layui-tab-card{
        border-top: none;
    }
    .select-form-box{
        padding: 10px 10px 0 15px;
        min-height: 400px;
    }
    .btn-subform, .query-btn{
        height: 30px;
        line-height: 30px;
        font-weight:600;
        padding-left: 31px;
        color: #FFFFFF;
        cursor: pointer;
    }
    .btn-subform{
        width: 96px;
        background: url('/dist/style/res/formFill/form-submit.png') no-repeat #2669B1;
        background-position: 7px 5px;
    }
    .query-btn{
        width: 71px;
        background: url('/dist/style/res/formFill/search.png') no-repeat 10px center;
        background-color: #77AF6F;
        margin-right: 10px;
    }
    .layui-tab-content{
        padding: 15px 9px;
    }
    .layui-table tbody tr.bgRed{
        background: red;
    }
    #test-table-cellEdit1{
        width: 100%;
        text-align: center;
    }
    .addLine, .delLine, .checkLine{
        position: relative;
        width: 24px;
        height: 22px;
        border: none;
        background-position: center center;
        background-repeat: no-repeat;
        margin-top: 4px;
        cursor: pointer;
    }
    .addLine{
        background: url(../../../../dist/style/res/formFill/add.png);
        margin-right: 40px;
    }
    .delLine{
        background: url(../../../../dist/style/res/formFill/del.png);
    }
    .checkLine{
        background-color: transparent;
        border: 1px solid #FF4E32;
        border-radius: 2px;
    }
    .checkLine .layui-icon{
        position: absolute;
        top: -1px;
        left: 2px;
        font-size: 19px;
        color: #FF4E32 !important;
		border-color: #FF4E32;
    }
    .layui-table[lay-even] tbody tr:nth-child(odd) {
        background: #D3E5FF;
    }
    .layui-table[lay-even] tbody tr:nth-child(even) {
        background: #fff;
    }
    .layui-table thead tr {
        background-color: #2669B1 !important;
        color: #fff;
    }
    .layui-table td, .layui-table th{
        text-align: center;
    }

    .left-card-body{
        box-sizing: border-box;
        height: 100%;
        padding: 10px 0 0 0;
        overflow-y: scroll;
    }
    .left-card-body .layui-form-label{
        line-height: inherit;
        color: #373737;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .left-card-body .layui-inline{
        width: 33%;
        margin-bottom: 15px;
    }
    .left-card-body .layui-input, .left-card-body select{
        width: 100%;
        padding-left: 10px;
        height: 37px;
        line-height: 37px;
        border: 1px solid #E4E4E4;
        border-radius: 6px;
        background-color: #F0F5F7;
    }
    .left-card-body .layui-input-inline{
        width: 200px;
    }
    .right-card-body{
        position: relative;
        float: right;
        width: 15.7%;
        height: 146px;
    }
    .kqform-content {
        overflow: auto;
    }
    .query-condition{
        height: 146px;
    }
    .layui-table th{
        overflow: hidden;
    }
    /* 人员节点 展开、折叠*/
    .ztree li span.button.diy01_ico_open, .ztree li span.button.diy01_ico_close{
        background-image: url('/start/plugin/zTree/css/zTreeStyle/img/icon-role.png');
    }
    /* 父节点展开 */
    .ztree li span.button.diy02_ico_open{
        background-image: url('/start/plugin/zTree/css/zTreeStyle/img/zTreeStandard.png');
        background-position: -110px -16px;
    }
    /* 父节点折叠 */
    .ztree li span.button.diy02_ico_close{
        background-image: url('/start/plugin/zTree/css/zTreeStyle/img/zTreeStandard.png');
        background-position: -110px 0;
    }

    /* 子节点 */
    .ztree li span.button.diy02_ico_docu{
        background-image: url('/start/plugin/zTree/css/zTreeStyle/img/zTreeStandard.png');
        background-position: -110px 0;
    }
    .ztree li span.button.diy01_ico_docu{
        background-image: url('/start/plugin/zTree/css/zTreeStyle/img/icon-role.png');
    }
    .ztree .no-data-tips{
        margin-top: 100px;
    }
    .layui-tab-content .layui-table th{
        border: 1px solid #e6e6ee;
    }
</style>
<script>
    layui.use(['admin', 'table', 'element', 'tools', 'laytpl', 'form', 'laydate'], function(){
        var table = layui.table,
            element = layui.element,
            admin = layui.admin,
            view = layui.view,
            setter = layui.setter,
            tools = layui.tools,
            laytpl = layui.laytpl,
            form = layui.form,
            laydate = layui.laydate,
            router = layui.router();

        var colName = [], //列名
            tablename = [], //表单名
            condition= [], //查询条件
            supContent = [],
            delRows = [],
            layout = ['.layui-table th', '.layui-table td', '#data-dataSearch-kqform', '.ztree'];
            window.tabIndex = 0; //选项卡下标 默认为0
            window.tableId = 'test-table-cellEdit1'; //选项卡表单id
            window.Id = '';
            window.taskId = '';
            window.link = '';
            window.taskname = '';
            window.checking = '';

        var setting = {
            data: {
                key: {
                    name: 'nodename'
                },
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: 0
                }
            },
            async: {
                enable: true,
                type: 'get',
                url: 'myapi/DC/api/rest/web/custom/GetTaskTree?access_token='+layui.data('layuiAdmin').access_token,
                dataFilter: ajaxDataFilter,
                autoParam: ['id']
            }, 
            callback: {
                onClick: zTreeOnClick
            }
        };

        // tools.initCite(router, {kqfirstMenu: '考勤管理', kqsecondMenu: '考勤查询'}, {czfirstMenu: '考勤管理', czsecondMenu: '考勤查询'}); 
        urgeDisplay(router.search);
        getTaskTree(); 
        addToolListen(); 
        changeTab(); 

        //处理回调数据
        function ajaxDataFilter(treeId, parentNode, responseData){
            var nodesData = [];
            if (responseData.retcode === '0' && responseData.data && responseData.data.length >0) {
                $.each(responseData.data, function (index, item) {
                    var writetype = item.writetype;
                    if(writetype == '2'){
                        item.iconSkin = 'diy02';
                        item.isParent = true;
                    }else if(writetype == '3'){
                        item.iconSkin = 'diy01';
                    }
                    nodesData.push(item);
                })
            }
            return nodesData;
        }

        //渲染任务树
        function getTaskTree(){
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/GetTaskTree',
                type: 'post',
                done: function(res){
                    if(res.retcode == '0' && res.data && res.data.length > 0){
                        var zNodes = [];
                        layui.each(res.data, function(index, item){ //异步加载需要给第一级节点帮点isParent:true
                            var writetype = item.writetype;
                            if(writetype == '2'){
                                item.iconSkin = 'diy02';
                                item.isParent = true;
                            }else if(writetype == '3'){
                                item.iconSkin = 'diy01';
                            }
                            item.rootNode = '1';
                            zNodes.push(item);
                        })
                        var zTree =  $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                        var nodes = zTree.getNodes();
                        if(nodes.length > 0){
                            zTree.selectNode(nodes[0]); //默认选中指定节点
                            if(nodes[0].checking === '1') {
                                getKqTaskForm(nodes[0].id, nodes[0].taskid, nodes[0].link);
                                pickTypeShow('kqform');
                            }else {
                                getTaskForm(nodes[0].id, nodes[0].taskid, nodes[0].link); //默认展示第一个节点表单
                                pickTypeShow('other');
                            }
                            window.Id = nodes[0].id;
                            window.taskId = nodes[0].taskid;
                            window.link = nodes[0].link;
                            window.taskname = nodes[0].nodename;
                            window.checking = nodes[0].checking;
                        }
                    }else {
                        var noDataHtml = '<div class="no-data-tips"><img src="/src/style/res/about/empty.png"><p style="color:#DBDBDB;">暂无数据</p></div>';
                        $('#treeDemo').empty().html(noDataHtml);
                        $('.form-tab-content').empty().html(noDataHtml);
                        $('.form-box').attr('style', 'height: 842px');
                    }
                }
            })
        }

        //任务树点击回调
        function zTreeOnClick(event, treeId, treeNode) {
            supContent = [];
            var flag = treeNode.rootNode && treeNode.rootNode == '1';
            flag ?  $('.layui-btn-urge').addClass('layui-btn-disabled') : $('.layui-btn-urge').removeClass('layui-btn-disabled');
            if(treeNode.checking === '1') {
                getKqTaskForm(treeNode.id, treeNode.taskid, treeNode.link);
                pickTypeShow('kqform');
            }else {
                getTaskForm(treeNode.id, treeNode.taskid, treeNode.link);
                pickTypeShow('other');
            }
            window.taskId = treeNode.taskid;
            window.Id = treeNode.id;
            window.link = treeNode.link;
            window.checking = treeNode.checking;
            window.tabIndex = 0; //切换为默认状态
            window.tableId = 'test-table-cellEdit1';
            window.taskname = treeNode.nodename;
        }

        //不同任务类型做不同的元素切换
        function pickTypeShow(type) {
            if(type === 'other') {
                $('.otherForm-content').show();
                $('.kqform-content').hide();
                $('.kq-time').hide();
            }else if(type === 'kqform') {
                $('.otherForm-content').hide();
                $('.kqform-content').show();
                $('.kq-time').show();
            }
        }

        //考勤查询页面隐藏催办按钮
        function urgeDisplay(search){
            search.kq && search.kq == '1' ? $('.layui-btn-urge').hide() : '';
        }

        function initLaydate(){
            var commonMin = { year: 1900, month: 0, date: 1},
                commonMax = { year: 2099, month: 11, date: 31};
            var startDate = laydate.render({
                elem: '.condition-starttime',
                done: function (value, date) {
                    if(!!value) {
                        endDate.config.min = {
                            year:date.year,
                            month:date.month-1, 
                            date: date.date,
                        };
                    }else {
                        endDate.config.min = commonMin;
                        endDate.config.max = commonMax;
                    }
                }
            });
            var endDate = laydate.render({
                elem: '.condition-endtime',
                done: function (value, date) {
                    if(!!value) {
                        startDate.config.max = {
                            year: date.year,
                            month: date.month - 1,
                            date: date.date,
                        } 
                    }else {
                        startDate.config.min = commonMin;
                        startDate.config.max = commonMax; 
                    }
                }
            });
        }

        //考勤任务表格详情加载
        function getKqTaskForm(id, taskid, link) {
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/GetFormDataByTaskid',
                type: 'post',
                data: {
                    id: id, 
                    taskid: taskid,
                    link: link,
                    checking: '1'
                },
                success: function(res) {
                    var kqdata = res.data.data;
                    var html = '<div class="query-box">'+
                                    '<div class="layui-row query-condition">'+
                                        '<div class="layui-col-md12 left-card-body">'+
                                            '<div class="layui-inline">'+
                                                '<label class="layui-form-label">用户姓名：</label>'+
                                                '<div class="layui-input-inline">'+
                                                    '<input type="text" name="writeusername" datatype="varchar" autocomplete="off" class="layui-input">'+
                                                '</div>'+
                                            '</div>'+
                                        '</div>'
                                    '</div>'+
                                '</div>';
                    $('#layui-query-box').empty().html(html);
                    $('.kq-starttime').html(kqdata.starttime);
                    $('.kq-endtime').html(kqdata.endtime);
                    renderKqTable(kqdata, taskid);
                    tools.setFont(layout);
                }
            });
        }
        
        //填报表单详情列表加载
        function getTaskForm(id, taskid, link, deptId){
            tablename = [];
            condition = [];
            var deptId = deptId ? deptId : '';
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/GetFormDataByTaskidShow',
                type: 'post',
                data: {
                    id: id, 
                    taskid: taskid,
                    link: link,
                    dept_id: deptId
                },
                success: function(res) {
                    window.FormData = res.data;
                    if(res.retcode == '0' && res.data && res.data.length > 0){
                        loadApply(res.data[window.tabIndex].condition, res.data[window.tabIndex].supcontent);
                        setUnitRadios(FormData[0], deptId);
                        $('#'+window.tableId).empty();
                        var titleHtml = '',
                            tableHtml = '';
                        for(var i = 0; i < res.data.length; i++){
                            if(i == window.tabIndex){ 
                                titleHtml +=  '<li class="layui-this">'+res.data[i].formname+'</li>';
                                tableHtml += '<div class="layui-tab-item layui-show" id='+res.data[i].id+'>'+
                                                '<table id="test-table-cellEdit'+(i+1)+'" lay-filter="test-table-cellEdit'+(i+1)+'"></table>'+
                                            '</div>';
                            }
                            else{ 
                                titleHtml += ' <li>'+res.data[i].formname+'</li>';
                                tableHtml += '<div class="layui-tab-item" id='+res.data[i].id+'>'+
                                                '<table id="test-table-cellEdit'+(i+1)+'" lay-filter="test-table-cellEdit'+(i+1)+'"></table>'+
                                            '</div>';
                            }
                        }
                        $('.form-tab-title').empty().html(titleHtml);
                        $('.form-tab-content').empty().html(tableHtml);
                        layui.each(res.data, function(index, item){
                            var field = item.form_field,
                                cols = item.cols,
                                tbody = item.data.grid,
                                warnResults = item.dv_results,
                                colsss = [],
                                colData = [],
                                fieldRole = item.fieldRole,
                                finalCols = [],
                                obj = new Object(),
                                selfId = item.id,
                                maxRow  = 1;

                            tablename.push(item.tablename);
                            condition.push(item.condition);
                            supContent.push(item.supcontent);
                            //得到数据标题行
                            $.each(field,function(index, item) {
                                $.each(fieldRole, function(i, role){
                                    if(item.fieldenglish == role.fieldenglish){
                                        item.see = role.see;
                                        item.edit = role.edit;
                                    }
                                })
                                colName.push(item.fieldenglish);
                                if(item.datatype != 'date'){
                                    var see = item.see,
                                        edit = item.edit;
                                    if(see != '0'){ 
                                        var param = {
                                            field: item.fieldenglish,
                                            title: item.fieldname,
                                            minWidth: 250,
                                        };
                                        param.event = edit && edit == '0' ? 'mustFill' : [item.nonull, item.datatype];
                                        finalCols.push(param);
                                    }
                                }else{
                                    if(item.see != '0'){ 
                                        finalCols.push({
                                            field: item.fieldenglish,
                                            title: item.fieldname,
                                            minWidth: 250,
                                            event: [item.nonull, item.datatype],
                                            templet: '#datetime'
                                        });
                                    }
                                }
                            });
                            
                            colsss = tools.handleCols(cols, finalCols);
                            layui.each(colsss, function(i, col){
                                i == colsss.length-1 && col.push({ align: 'center', title:'操作', toolbar : '#modify-form', rowspan: colsss.length });
                            });		
                            tools.addOtherCols(colsss, true);	
													
                            if(tbody.length > 0){ 
                                colData = tbody;
                                layui.each(colData, function(index, item){
                                    item.model = 'normal';
                                    item.tableId = selfId;
                                })
                            }else{ 
                                for(var i = 0; i < maxRow; i++){
                                    var blankLine = {};
                                    for(var j = 0; j < colName.length; j++){
                                        blankLine[colName[j]] = "";
                                        blankLine.model = "insert";
                                        blankLine.id = createUniqueId(1);
                                        blankLine.tableId = selfId;
                                    }
                                    colData.push(blankLine);
                                }
                            }                                                             
                            tools.handleWarnInfo(colsss, warnResults);
                            var options = {
                                elem: '#test-table-cellEdit'+(index+1)
                                ,cols: colsss
                                ,text: {
                                    none: '<div class="no-data-tips"><img src="/src/style/res/about/empty.png"><p style="color:#DBDBDB;">暂无数据</p></div>'
                                }
                                ,skin: 'nob'
                                ,height: 500
                                ,even: true
                                ,limit: 5000
                                ,initSort: {
                                    field: 'statename',
                                    type: 'desc' //asc 升序 desc 降序
                                }
                                ,data: colData
                                ,done: function(res, curr, index){
                                    if(res.data && res.count > 0){
                                        var data = res.data;
                                        $('.layui-input-date').each(function(index, item){
                                            var field = $(this).parents('td').data('field'),
                                                datatime = data[index][field] ? $.trim(data[index][field]) : '';                                            
                                            laydate.render({
                                                elem: this,
                                                type: 'date',
                                                format: 'yyyy-MM-dd',
                                                isInitValue: true, 
                                                value: datatime, 
                                                trigger: 'click'
                                            });
                                        });
                                        layui.each(colsss[colsss.length-1], function(index, item){
                                            if(item.title && item.title.length >= 20){
                                                var th = $('th[data-field='+item.field+']');
                                                th.find('span').attr('lay-tips', item.title);
                                            }
                                        });
                                        form.render('select', 'tabSwitch');
                                    }
                                    tools.setFont(layout);
                                }
                            }
                            table.render(options);
                        })
                    }else{
                        $('.form-tab-title').empty();
                        $('#'+window.tableId).next().find('.layui-table-box').empty();
                        $('.form-tab-content').empty().html('<div class="no-data-tips"><img src="/src/style/res/about/empty.png"><p style="color:#DBDBDB;">暂无数据</p></div>');
                    }
                }
            })
        }

        //设置填报表单单位单选框
        function setUnitRadios(data, checkId){
            var deptMsgs = data.deptMsgs || [],
                view = document.getElementById('dept'),
                getTpl = unitRadios.innerHTML;
            if(deptMsgs && deptMsgs.length > 0){
                deptMsgs && deptMsgs[0].dept_name != '全部' ? deptMsgs.unshift({dept_name: '全部', dept_id: ''}) : '';
                layui.each(deptMsgs, function(index, item){
                    item.checked = false;
                    item.dept_id == checkId ? item.checked = true : ''
                });
            }
            laytpl(getTpl).render(deptMsgs, function(html){
                view.innerHTML = html;
            });
            form.render('radio', 'tabSwitch');
        }

        //监听Tab切换
        element.on('tab(tabSwitch)', function(data){
            var index = data.index + 1;
            window.tableId = 'test-table-cellEdit'+index; 
            window.tabIndex = data.index; 
            addToolListen();
            changeTab();
            loadApply(condition[data.index], supContent[data.index]);
            setUnitRadios(FormData[tabIndex], '');
        });

        //监听单位单选框单选
        form.on('radio(custom-unit-radio)', function(data){
            getTaskForm(window.Id, window.taskId, window.link, data.value);
        });

        //表单详情表格 => 监听表格新增行删除行 
        function addToolListen(){
            table.on('tool('+window.tableId+')', function(obj){
                var event = obj.event,
                    data = obj.data;
                if(event === 'addLine'){
                    var Data = table.cache[""+window.tableId+""], //当前表格所有数据
                        randomId = createUniqueId(1),
                        datas = { model: "insert", id: randomId };
                    for(var i = 0; i < colName.length; i++){
                        datas[colName[i]] = "";
                    }
                    Data.push(datas);
                    table.reload(window.tableId,{ data: Data });
                    layer.closeAll('tips');
                }else if(event === 'delLine'){
                    var Data = table.cache[""+window.tableId+""],
                        index = obj.tr.data('index'),
                        randomId = createUniqueId(1);
                    layer.confirm('真的删除当前行么？', function(index2){
                        if(obj.data.model == 'normal'){
                            deleteRow(obj.data); 
                        }
                        Data.splice(index, 1);
                        obj.data.model = 'del';
                        delRows.push(obj.data);
                        if(index == 0){
                            var datas = { model: "insert", id: randomId }
                            for(var i = 0; i < colName.length; i++){
                                datas[colName[i]] = "";
                            }
                            Data.push(datas);
                        } 
                        table.reload(window.tableId,{ data: Data });
                        layer.close(index2);
                    });
                    layer.closeAll('tips');
                }else if(event == 'check'){
                    admin.req({
                        url: 'myapi/DC/api/rest/web/custom/GainHistory',
                        data: {
                            id: data.id
                        },
                        done: function(res){
                            if(res.retcode == '0'){
                                if(res.data && res.data.length > 0){
                                    var taskrecode = layer.open({
                                        id: 'temporary-addhtml',
                                        title:'<i class="formFill-icon"></i><span style="color:#FFF;">查看记录</span>',
                                        offset: '110px',
                                        type: 1,
                                        shadeClose: true,
                                        area: ['700px', '420px'],
                                        resize: false,
                                        success: function(lay, index){
                                            view(this.id).render('./task/temporary/history', {history: res.data});
                                        }
                                    })
                                }else{
                                    layer.msg('暂无记录', {time: 1000});
                                }
                            }
                        }
                    })
                }
            })
        }

        //表单详情表格 => 监听单元格编辑
        function changeTab(){
            table.on('edit('+window.tableId+')', function(obj){
                var selector = 'div[lay-id="'+window.tableId+'"] '+obj.tr.selector+' td[data-field="'+obj.field+'"] div'; //获取编辑前的值
                var oldVal = $(selector).text();
                var newVal = obj.value; //得到修改后的值
                var data = obj.data; //得到所在行所有键值
                var Data = table.cache[''+window.tableId+'']; //表格所有信息
                var index = obj.tr.data('index'); //当前编辑行index
                var model = data.model; //当前行的model状态
                var td = 'div[lay-id="'+window.tableId+'"] '+obj.tr.selector+' td[data-field="'+obj.field+'"]';
                var dataType = $(td).attr('lay-event').split(',')[1]; //当前字段的数据类型
                if(newVal != oldVal && oldVal != '' && model == 'normal'){
                    Data[index].model = 'update';   
                    table.reload(window.tableId,{
                        data: Data
                    })
                }
                inputVertify(newVal, dataType, selector);
            });
        }

        //字段验证
        function inputVertify(newVal, dataType, selector){
            var reg = null,
                text = '';
            if(dataType == 'varchar'){
                reg = /^[\u0391-\uFFE5]+$/;
                text = '字符';
            }else if(dataType == 'integer'){
                reg = /^[0-9]+$/;
                text = '整数';
            }else if(dataType == 'date'){
                reg = /^(\d{4})-(\d{2})-(\d{2})$/;
                text = '日期';
            }
            if(newVal.trim() != '' && !reg.test(newVal.trim())){
                layer.msg('该列字段类型为'+text+'格式，请正确输入！', {time: 1000});
                $(selector).parent().css('background-color','orange');
            }else{
                $(selector).parent().css('background-color', 'transparent');
            }
        }

        //按钮点击事件
        $('.T-btn').click(function(){
            var target = $(this).data('target');
            if(target == 'save'){
                var idState= table.cache[''+window.tableId+''];                 
                var allData;
                if(idState){
                    allData = tools.getTableData(window.tableId, 'tbody');
                }
                if(delRows.length > 0){
                    allData = allData.concat(delRows);
                }
                for(var i = 0; i < allData.length; i++){
                    delete allData[i].LAY_TABLE_INDEX;
                    delete allData[i].dataplace;
                    delete allData[i].taskid;
                    allData[i].id = idState[i].id;
                    allData[i].model = idState[i].model;
                }
                var tablebody =  $('#'+window.tableId).next().find('.layui-table-body tbody tr');
                var flag = true;
                $.each(tablebody, function(i, eachTr){
                    var allTd = eachTr.querySelectorAll('td');
                    $.each(allTd, function(i2, eachTd){
                        if(!eachTd.getAttribute('class')){
                            if(eachTd.getAttribute('style')){ //验证必填项
                                flag = false;
                                return false
                            }
                            var dataType = eachTd.getAttribute('lay-event').split(',')[1]; //当前字段的数据类型 
                            var reg = null,
                                text = '',
                                newVal = eachTd.querySelector('div').innerText;  
                            if(dataType == 'varchar'){ //验证字段类型
                                reg = /^[\u0391-\uFFE5]+$/; 
                                text = '字符';
                            }else if(dataType == 'integer'){
                                reg = /^[0-9]+$/;
                                text = '整数';
                            }else if(dataType == 'date'){
                                reg = /^(\d{4})-(\d{2})-(\d{2})$/;
                                text = '日期';
                            }
                            if(newVal.trim() != '' && !reg.test(newVal.trim())){
                                eachTd.setAttribute('style','background-color: orange');
                                flag = false;
                                layer.msg('该列字段类型为'+text+'格式，请正确输入！', {time: 1000});
                                return false;
                            }
                        }
                    })
                })
                if(flag){
                    if(allData && allData.length > 0){
                        admin.req({
                            url: 'myapi/DC/api/rest/web/custom/FormDataOper',
                            type: 'post',
                            data: {
                                griddata: JSON.stringify(allData),
                                tablename: tablename[window.tabIndex],
                                taskid: window.taskId,
                                formdata: '',
                            },
                            success: function(res){
                                if(res.retcode == '0'){
                                    layer.msg('保存成功', {time: 1000})
                                    handleErrorRow(res.data, allData);
                                }
                            }
                        })
                    }else{
                        layer.msg('没有需要保存的数据', {time: 1000});
                    }
                }
            }else if(target == 'submit'){
                var formdata = window.FormData;
                if(window.checking === "1") {
                    var aWriteName = $('.left-card-body').find('input[name="writeusername"]').val(),
                        url = 'myapi/DC/api/rest/web/custom/checkworkExportExcel';
                    tools.downLoadfunction(url,{
                        taskid: window.taskId,
                        id: window.Id,
                        writeusername: aWriteName,
                        access_token: layui.data(setter.tableName)[setter.request.tokenName]
                    });
                }else {
                    if(formdata && formdata.length > 0){
                        var sheet = [];
                        layui.each(formdata, function(index, item){
                            var obj = new Object();
                            obj.formname = item.formname;
                            obj.header = JSON.stringify(tools.getSerachData('test-table-cellEdit'+(index+1), 'thead'));
                            obj.data = JSON.stringify(tools.getSerachData('test-table-cellEdit'+(index+1), 'tbody'));
                            sheet.push(obj);
                        })
                        var url = 'myapi/DC/api/rest/web/custom/taskExcelDataDownload';
                        tools.downLoadfunction(url,{
                            taskname: window.taskname,
                            sheets: JSON.stringify(sheet),
                            access_token: layui.data(setter.tableName)[setter.request.tokenName]
                        });
                    }else{
                        layer.msg('没有需要导出的数据', {time: 1000});
                    }
                }
            }else if(target == 'urge'){
                var isDisalbed = $(this).hasClass('layui-btn-disabled');
                if(isDisalbed){
                    return ;
                }
                layer.open({
                    id: 'urgememo',
                    type: 1,
                    title: '<i class="formFill-icon"></i><span style="color:#FFF;">催办消息</span>',
                    area: ['300px', '250px'],
                    offset: 'auto',
                    shadeClose: true,
                    resize: false,
                    success: function(lay, index){
                        view(this.id).render('./audit/components/usermemo', {
                            showReview: false
                        });
                    },
                    btn: ['确定', '取消'],
                    btnAlign: 'c',
                    yes: function(index, layero){
                        var memoval = $('#urgememo .layui-textarea').val();
                        if($.trim(memoval) == ''){
                            layer.msg('请填写催办消息', {time: 1000});
                            return ;
                        }
                        admin.req({
                            url: 'myapi/DC/api/rest/web/custom/Pressdo',
                            type: 'post',
                            data: {
                                model: 'add',
                                taskid: window.taskId,
                                writeid: window.Id,
                                memo: memoval
                            },
                            done: function(res){
                                if(res.retcode == '0'){
                                    layer.msg('催办成功', {time: 1000});
                                    layer.close(index);
                                }
                            }
                        })
                    }
                })
            }
        })
        
        //查询事件
        $('.form-box').delegate('#query', 'click', function(){
            var allInput = $('.left-card-body input'),
                allSelect = $('.left-card-body select'),
                allOpt = [],
                InputDatas = getQueryData(allInput),
                selectDatas = getQueryData(allSelect),
                allOpt = InputDatas.concat(selectDatas);
            if(window.taskId){
                admin.req({
                    url: 'myapi/DC/api/rest/web/custom/GetDataByCon',
                    data: {
                        tablename: tablename[window.tabIndex],
                        taskid: window.taskId, 
                        id: window.Id,
                        checking: window.checking,
                        where: JSON.stringify(allOpt)
                    },
                    success: function(res){
                        if(res.retcode == '0'){
                            layer.msg('查询成功', {time: 1000});
                            window.checking === '1'  ? renderKqTable(res.data.data, window.taskId) : hanleQueryForm(res.data.grid);
                        }
                    }
                });
            }else{
                layer.msg('暂无查询条件', {time: 1000});
            }
        });
        
        //给enter绑定查询
        $('body').keydown(function(){
            if(event.keyCode == '13'){
                $('#query').click();
            }
        });

        //生成唯一id
        function createUniqueId(n) {
            var random = function() { // 生成10-12位不等的字符串
                return Number(Math.random().toString().substr(2)).toString(36); // 转换成十六进制
            }
            var arr = [];
            function createId() {
                var num = random();
                var bool = false;
                for(var i = 0; i < arr.length; i++){
                    if(arr[i] === num){
                        bool = true
                    }
                }
                if(bool) {
                    createId();
                }else {
                    arr.push(num);
                }
            }
            var i = 0;
            while(i < n) {
                createId();
                i++;
            }
            return arr[0];
        }

        //获取查询值
        function getQueryData(nodes){
            var data = [],
                keys = [];
            if(nodes && nodes.length > 0){
                $.each(nodes, function(index, item){
                    var name = item.name,
                        val = item.value,
                        type = $(this).attr('datatype');
                    if(!!val){
                        if(type == 'date'){
                            var starttime = $('.condition-starttime').val() || '',
                                endtime = $('.condition-endtime').val() || '',
                                time = starttime+','+endtime;
                            if(keys.indexOf(name) == -1){
                                keys.push(name);
                                data.push({ key: name, value: time, datatype: type });
                            }
                        }else if(type != 'date'){
                            data.push({ key: name, value: val, datatype: type });
                        }
                    }
                })
            }
            return data;
        }

        //删除表单详情表单行
        function deleteRow(row){
            if(row.id){
                delete row.dataplace;
                delete row.taskid;
            }
            row.model = 'del';
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/FormDataOper',
                type: 'post',
                data: {
                    griddata: JSON.stringify([row]),
                    tablename: tablename[window.tabIndex],
                    taskid: window.taskId,
                    formdata: ''
                },
                success: function(res){
                    if(res.retcode == '0'){
                        layer.msg('删除成功', {time: 1000});
                    }
                }
            })
        }

        //处理保存出错的表单行
        function handleErrorRow(failData, data){
            var idsArray = failData.ids.split(','); //保存出错行的id数组
            for(var i = 0; i < idsArray.length; i++){
                for(var j = 0; j < data.length; j++){
                    if(idsArray[i] == data[j].id){
                        var elem = $('#'+window.tableId).next();
                        var tr = elem.find('.layui-table-box tbody tr[data-index="'+j+'"]');
                        tr.css({
                            'background-color':'pink',
                            'border-bottom': '1px solid #ccc'
                        });
                    }
                }
            }
        }

        //加载查询条件
        function loadApply(field, content){
            if(field && field.length > 0){
                layui.each(field, function(index, item){
                    for(var key in content){
                        if(item.fieldenglish == key){
                            item.isSelect = true;
                            item.selectData = content[key];
                        }
                    }
                });
            }
            var getTpl = queryExihibt.innerHTML,
                $view = document.getElementById('layui-query-box');
            laytpl(getTpl).render(field, function(html){
                $view.innerHTML = html;
            });
            $('.condition-starttime') && initLaydate();
            form.render('select', 'query-condition-filter');
        }

        //处理查询结果
        function hanleQueryForm(queryData){
            if(queryData.length > 0){
                for(var i = 0; i < queryData.length; i++){
                    delete queryData[i].dataplace;
                    delete queryData[i].taskid;
                }
            }else{
                layer.msg('未查询到数据', {time: 1500});
            }
            table.reload(window.tableId,{
                data: queryData
            })
        }

        function renderKqTable(data, taskid) {
            var dates = data.users.length > 0 ? data.users[0].users_time[0].users_time_day : [],
                users = data.users;
            view('data-dataSearch-kqform').render('./data/kqTable', {
                dates: dates, 
                users: users,
                basic: {
                    dept_code: data.dept_code,
                    dept_name: data.dept_name,
                    dept_id: data.dept_id,
                    taskid: taskid
                }
            });
        }


    })
</script>